package world.criver.h50909.function;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;

public class funHttp {
    public String get(String url, HashMap<String,String> params){
        try {
//            System.out.println("[request][GET]"+url + paramsToString(params));
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .GET()
                    .uri(URI.create(url + paramsToString(params)))
                    .timeout(Duration.ofSeconds(2))
                    .build();
            HttpResponse<String> response= client.send(request,HttpResponse.BodyHandlers.ofString());
//            System.out.println("[response][GET]"+response.body());
            return response.body();
        }catch (Exception e){
//            e.printStackTrace();
            return null;
        }
    }
    public String post(String url, HashMap<String,String> params, ObjectNode body){
        try{
//            System.out.println("[request][POST]"+url + paramsToString(params)+"\n"+((body==null || body.isEmpty())?HttpRequest.BodyPublishers.noBody():HttpRequest.BodyPublishers.ofString(body.toString())));
            HttpClient client=HttpClient.newHttpClient();
            HttpRequest request= HttpRequest.newBuilder()
                    .POST((body==null || body.isEmpty())?HttpRequest.BodyPublishers.noBody():HttpRequest.BodyPublishers.ofString(body.toString()))
                    .timeout(Duration.ofSeconds(2))
                    .uri(URI.create(url+paramsToString(params)))
                    .build();
            HttpResponse<String> response= client.send(request,HttpResponse.BodyHandlers.ofString());
//            System.out.println("[response][POST]"+response.body());
            return response.body();
        }catch (Exception e){
//            e.printStackTrace();
            return null;
        }
    }
    private String paramsToString(HashMap<String,String> params){
        if(params==null)return "";
        StringBuilder p= new StringBuilder();
        for(String k: params.keySet()) p.append("&").append(k).append("=").append(params.get(k));
        return (!p.isEmpty()) ?("?"+p):"";
    }
}